﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
using Kratos.Framework.Extensions;

namespace Kratos.Framework.Filters.ModelMetadata
{
    public class StyleEditorAttribute : Attribute, IMetadataAware
    {
        /// <summary>
        /// 类集合
        /// </summary>
        private readonly IList<string> _styles = new List<string>();

        private readonly string _class;

        /// <summary>
        /// 资源文件类
        /// </summary>
        public Type ResourceType;

        /// <summary>
        /// 显示名称
        /// </summary>
        public string DisplayName { get; set; }

        public StyleEditorAttribute(string classes)
        {
            _class = classes;
        }

        public StyleEditorAttribute(params string[] classes)
            : this(string.Join(" ", classes))
        {
        }

        public void OnMetadataCreated(System.Web.Mvc.ModelMetadata metadata)
        {
            DisplayName = DisplayName.NotNullOrEmpty()
                              ? DisplayName
                              : metadata.PropertyName.NotNullOrEmpty() ? metadata.PropertyName : metadata.ModelType.Name;

            metadata.DisplayName = ResourceType == null
                                       ? DisplayName
                                       : ResourceType.GetProperty(DisplayName,
                                                                  BindingFlags.NonPublic | BindingFlags.Public |
                                                                  BindingFlags.Static)
                                             .GetValue(null, null).ToString();

            _styles.Add("text-box");
            _styles.Add("single-line");
            if (metadata.DataTypeName == "Password")
            {
                _styles.Add("password");
            }

            _styles.Add(_class);

            if (_styles.Count <= 0) return;
            metadata.TemplateHint = "StyleEditor";
            metadata.AdditionalValues["Styles"] = string.Join(" ", _styles);
            metadata.ShowForEdit = true;
            metadata.ShowForDisplay = false;
            _styles.Clear();
        }
    }
}
